package com.heking.maplib;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author 35574
 * @Date 2021/9/16
 * @Description
 */
public class Utils {
    private static final String TAG = ">>>Utils";
    /**
     * 把assets目录中的文件copy到指定位置
     * @param context
     * @param assetPath 相对assets的路径
     * @param desPath 目的地址
     * @param existsSkip 如果文件已经存在且大小一样则跳过复制
     */
    public static void copyAssets(Context context,String assetPath, String desPath,boolean existsSkip){
        FileOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            File desFile=new File(desPath);
            //创建父目录
            if(!desFile.getParentFile().exists()){
                boolean mkdirs = desFile.mkdirs();
            }
            //创建文件
            if(!desFile.exists()){
                boolean newFile = desFile.createNewFile();
            }
            inputStream = context.getAssets().open(assetPath);
            if(!(existsSkip && inputStream.available()==desFile.length())){
                outputStream = new FileOutputStream(desFile);
                byte[] buf = new byte[1024];
                int len;
                while ((len=inputStream.read(buf))>0){
                    outputStream.write(buf,0,len);
                }
                outputStream.flush();
            }else{
                Log.d(TAG, "copyAssets:skip");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
